package com.android.fastride.manager;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.android.fastride.model.http.entity.LoginUserInfoEntity;
import com.peng.library.mantis.kit.Codec;
import com.peng.library.mantis.kit.Kits;


/**
 * 用户管理类
 * Created by pengyuantao on 2017/9/28 15:03.
 */

public class UserManager {

	private static final String TAG = "UserManager";

	public static final String KEY_USER_INFO = "KEY_USER_INFO";

	public static final String NAME_USER_INFO = "NAME_USER_INFO";

	//必须为16位种子
	public static final String NAME_USER_DES_SEED = "FastRide=\n";

	private LoginUserInfoEntity userInfo;

	//des的秘钥
	private String desKey = NAME_USER_DES_SEED;

	private static class Holder {
		static final UserManager instance = new UserManager();
	}

	public static UserManager getInstance () {
		return Holder.instance;
	}

	/**
	 * 初始化用户信息
	 *
	 * @param context
	 */
	public void init (Context context) {
		//读取SP数据并且进行解密token
		SharedPreferences sharedPreferences = context.getSharedPreferences(NAME_USER_INFO, Context.MODE_PRIVATE);
		//首先读取本地的des秘钥
		String userInfoText = sharedPreferences.getString(KEY_USER_INFO, null);
		if (!Kits.Empty.check(userInfoText)) {
			//解密并且进行解析
			try {
				String json = new String(Codec.DES.decrypt(Codec.BASE64.decode(userInfoText), desKey));
				userInfo = JSON.parseObject(json
						, LoginUserInfoEntity.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 刷新用户信息
	 *
	 * @param context
	 * @param userInfo
	 */
	public void refreshUserInfo (Context context, LoginUserInfoEntity userInfo) {
		this.userInfo = userInfo;
		SharedPreferences sharedPreferences = context.getSharedPreferences(NAME_USER_INFO, Context.MODE_PRIVATE);
		//重新创建一个对象并且将加密数据放进去
		String json = JSON.toJSONString(userInfo);
		//加密
		try {
			byte[] encrypt = Codec.DES.encrypt(json.getBytes(), desKey);
			sharedPreferences.edit().putString(KEY_USER_INFO, Codec.BASE64.encodeToString(encrypt)).apply();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回用户的token
	 *
	 * @return
	 */
	public String getUserToken () {
		return userInfo == null ? null : userInfo.getAuthtoken();
	}

	/**
	 * 返回用户的信息
	 *
	 * @return
	 */
	public LoginUserInfoEntity getUserInfo () {
		return userInfo;
	}

	/**
	 * 删除用户信息
	 */
	public void clearUserInfo (Context context) {
		userInfo = null;
		//删除用户信息文件
		context.getSharedPreferences(NAME_USER_INFO, Context.MODE_PRIVATE).edit().clear().apply();
	}

}
